<#assign steps=events?size >
SELECT
deviceId,
<#list events as eparam>
sequenceMatch('<#list 1..steps-eparam_index as n>.*(?${n})</#list>.*')(
toDateTime(`timeStamp`)
  <#list events as ev>
  ,eventId='${ev.eventId}'  <#list ev.properties?keys as key> AND properties['${key}']='${ev.properties[key]}'</#list>
 </#list>
) AS is_match${steps-eparam_index}<#if eparam_has_next>,</#if>
</#list>
FROM event_detail
WHERE deviceId=? AND `timeStamp` >= ? AND `timeStamp` <= ?
AND (
<#list events as ev>
  (eventId='${ev.eventId}'  <#list ev.properties?keys as key> AND properties['${key}']='${ev.properties[key]}')<#if ev_has_next> OR </#if></#list>
</#list>
)
GROUP BY deviceId
;